<?php

namespace app\erp\controller;

use app\erp\model\Invoicedb;
use app\erp\model\Cartdb;
use app\erp\model\Qingkuandb;
use app\erp\model\Shoppingdb;
use app\erp\model\Orderdb;
use app\erp\model\UInvoicedb;
use app\erp\model\UOrderdb;
use app\erp\model\Uploaddb;
use think\Cache;
use think\Db;
use function GuzzleHttp\json_decode;
use app\erp\model\OrderLogdb;

class Invoice extends Base
{
    protected $base_url = 'http://tailongji.dixintong.com/';
    protected $db;
    protected $cols = array(
        array(
            'field' => 'invoice_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
            'fixed' => 'left'
        ),
        array(
            'field' => 'invoice_type_text',
            'width' => 100,
            'title' => '发票类型'
        ),
        array(
            'field' => 'invoice_title',
            'width' => 300,
            'title' => '发票抬头'
        ),
        array(
            'field' => 'invoice_duty',
            'width' => 200,
            'title' => '税号'
        ),
        array(
            'field' => 'out_order_no',
            'width' => 200,
            'title' => '订单号'
        ),
        array(
            'field' => 'supplier_name',
            'width' => 200,
            'title' => '库房'
        ),
        array(
            'field' => 'invoice_money',
            'width' => 120,
            'title' => '开票金额'
        ),
        array(
            'field' => 'supplier_picture',
            'width' => 50,
            'title' => '章',
            'templet' => '#supplier_pictureTpl'
        ),
        array(
            'field' => 'state',
            'width' => 90,
            'title' => '用户发票',
            'templet' => '#stateTpl'
        ),
        array(
            'field' => 'order_shoukuan',
            'width' => 90,
            'title' => '收款状态',
            'templet' => '#order_shoukuanTpl'
        )
    );
    protected $cols2 = array(
        array(
            'field' => 'invoice_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
            'fixed' => 'left'
        ),
        array(
            'field' => 'invoice_title',
            'width' => 200,
            'title' => '发票抬头'
        ),
        array(
            'field' => 'invoice_duty',
            'width' => 100,
            'title' => '税号'
        ),
        array(
            'field' => 'out_order_no',
            'width' => 190,
            'title' => '订单号'
        ),

        array(
            'field' => 'supplier_name',
            'width' => 200,
            'title' => '库房'
        ),
        array(
            'field' => 'invoice_money',
            'width' => 120,
            'title' => '开票金额'
        ),
        array(
            'field' => 'caigou_invoice_duty',
            'width' => 120,
            'title' => '采购发票号'
        ),
        array(
            'field' => 'supplier_picture',
            'width' => 50,
            'title' => '章',
            'templet' => '#supplier_pictureTpl'
        ),
        array(
            'field' => 'state',
            'width' => 90,
            'title' => '用户发票',
            'templet' => '#stateTpl'
        ),

        array(
            'field' => 'order_shoukuan',
            'width' => 60,
            'title' => '收款',
            'templet' => '#order_shoukuanTpl'
        ),

        array(
            'field' => 'caigou_hetong',
            'width' => 90,
            'title' => '采购合同',
            'templet' => '#caigou_hetongTpl',
            'hide' => true
        ),
        array(
            'field' => 'gys_state',
            'width' => 90,
            'title' => '采购发票',
            'templet' => '#gys_stateTpl'
        ),
        array(
            'field' => 'caigou_state',
            'width' => 90,
            'title' => '发票审核',
            'templet' => '#caigou_stateTpl'
        ),
        array(
            'field' => 'order_fukuan',
            'width' => 60,
            'title' => '付款',
            'templet' => '#order_fukuanTpl'
        ),
        array(
            'fixed' => 'right',
            'width' => 60,
            'toolbar' => '#pinvoice_tool',
            'title' => '查看'
        )
    );
    public $post = array();

    // 下载电子发票到本地
    public function savelocation()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $url = $this->post['data_url'];
        $save_url = './uploads/invoice/' . $this->post['order_no'] . '_' . $this->post['invoice_id'] . '.pdf';
        file_put_contents($save_url, file_get_contents($url));
        $param ['size'] = 0;
        $param ['type'] = 'pdf';
        $param ['save_path'] = str_replace('uploads/', '', $save_url);
        $param ['file_name'] = $this->post['order_no'] . '_' . $this->post['invoice_id'] . '.pdf';
        $uploaddb = new Uploaddb();
        $uploaddb->param = $param;
        $info = $uploaddb->ajaxSave();
        $invoicedb = new Invoicedb();
        $get_invoice = $invoicedb->find($this->post['invoice_id']);
        $get_invoice->save(['invoice_proof' => $info['upload_id']]);
        $UInvoicedb = new UInvoicedb();
        $get_u_invoice = $UInvoicedb->where('order_nos', $get_invoice['order_nos'])->find();
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('order_no', $get_invoice['order_nos'])->find();
        $get_order->save(['is_down' => 1]);
        if ($get_u_invoice) {
            $save_data = [];
            $save_data['invoice_proof'] = $info['upload_id'];
            $save_data['state'] = $get_invoice['state'];
            $save_data['api_return_no'] = $get_invoice['api_return_no'];
            $save_data['fapiaohao'] = $get_invoice['fapiaohao'];
            $save_data['fapiaodaima'] = $get_invoice['fapiaodaima'];
            $get_u_invoice->save($save_data);
            // 同步订单状态
            $UOrderdb = new UOrderdb();
            $get_u_order = $UOrderdb->where('order_no', $get_invoice['order_nos'])->find();
            if ($get_u_order && $get_order) {
                $save_data = [];
                $save_data['invoice_state'] = $get_order['invoice_state'];
                $save_data['returncode'] = $get_order['returncode'];
                $get_u_order->save([
                    'invoice_state' => $get_order['invoice_state'],
                    'returncode' => $get_order['returncode'],
                    'is_down' => 1
                ]);
            }
        }
        Cache::clear('order');
        Cache::clear('invoice');
        $this->layuiReturn('下载成功');
    }

    // 推送发票到军采
    public function pushJunInvoice()
    {
        $out_order_no = $this->post['order_no'];
        $junapi = new \app\jun\controller\Api();
        $result = $junapi->sendInvoiceInfo($out_order_no);
        $this->layuiReturn($result['returnMsg']);
    }

    // 打包
    public function zipDown($out_order_no)
    {
        $zip_name = 'uploads/hetong/' . $out_order_no . '.zip';
        $zip = new \ZipArchive ();
        $res = $zip->open($zip_name, \ZipArchive::CREATE);
        if ($res === true) {
            $orderdb = new Orderdb ();
            $get_order = $orderdb->useGlobalScope(false)->where('out_order_no', $out_order_no)->find();
            if ($get_order) {
                $get_order = $get_order->toArray();
                if ($get_order ['cght']) {
                    $zip->addFile(str_replace($this->base_url, '', $get_order ['cght']));
                }
                if ($get_order ['shd']) {
                    $zip->addFile(str_replace($this->base_url, '', $get_order ['shd']));
                }
                if ($get_order ['xsht']) {
                    $zip->addFile(str_replace($this->base_url, '', $get_order ['xsht']));
                }
                if ($get_order ['xsfp']) {
                    $zip->addFile(str_replace($this->base_url, '', $get_order ['xsfp']));
                }
                if ($get_order ['cgfp']) {
                    $zip->addFile(str_replace($this->base_url, '', $get_order ['cgfp']));
                }
            }
        } else {
            print_r('创建失败');
        }
        $zip->close();
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length: " . filesize($zip_name));
        header("Content-Disposition: attachment; filename=\"" . basename($zip_name) . "\"");
        readfile($zip_name);
        @unlink($zip_name);
    }

    public function zipDownOne($out_order_no)
    {
        $zip_name = $out_order_no . '.zip';
        $zip = new \ZipArchive ();
        $res = $zip->open($zip_name, \ZipArchive::CREATE);
        if ($res === true) {
            $orderdb = new Orderdb ();
            $get_order = $orderdb->useGlobalScope(false)->where('out_order_no', $out_order_no)->find();
            if ($get_order) {
                $get_order = $get_order->toArray();
                if ($get_order ['cght']) {
                    $zip->addFile('uploads/Excel/hetong/' . $out_order_no . '采购合同.pdf', $out_order_no . '采购合同.pdf');
                }
                if ($get_order ['shd']) {
                    $zip->addFile('uploads/Excel/hetong/' . $out_order_no . '送货验收单.pdf', $out_order_no . '送货验收单.pdf');
                }
                if ($get_order ['xsht']) {
                    $zip->addFile('uploads/Excel/hetong/' . $out_order_no . '销售合同.pdf', $out_order_no . '销售合同.pdf');
                }
                if ($get_order ['xsfp']) {
                    $zip->addFile(str_replace($this->base_url, '', $get_order ['xsfp']), $out_order_no . '销售发票.xls');
                }
                if ($get_order ['cgfp']) {
                    $zip->addFile(str_replace($this->base_url, '', $get_order ['cgfp']), $out_order_no . '采购发票.xls');
                }
            }
        } else {
            print_r('创建失败');
        }
        $zip->close();
        // readfile ( $zip_name );
        return $zip_name;
    }

    public function zipDownAll($out_order_no)
    {
        $out_order_no = explode(',', $out_order_no);
        $zip_name = 'uploads/zipdown/' . date('YmdHis') . rand(100, 999) . '.zip';
        $file_name_arr = array();
        $zip_all = new \ZipArchive ();
        $res = $zip_all->open($zip_name, \ZipArchive::CREATE);
        if ($res) {
            foreach ($out_order_no as $key => $val) {
                $file_name = $this->zipDownOne($val);
                $zip_all->addFile($file_name);
                array_push($file_name_arr, $file_name);
            }
        } else {
            echo '错误';
        }
        $zip_all->close();
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length: " . filesize($zip_name));
        header("Content-Disposition: attachment; filename=\"" . basename($zip_name) . "\"");
        readfile($zip_name);
        @unlink($zip_name);
        foreach ($file_name_arr as $key => $val) {
            @unlink($val);
        }
    }

    public function _initialize()
    {
        parent::_initialize();
        $request = request();
        $param = $request->param();
        $this->post = $param;
        $this->db = new Invoicedb ();
        $this->db->param = $this->post;
    }

    // 独立开票
    public function saveAloneInvoice()
    {
        $return = $this->db->makeInvoice();
        $this->layuiReturn('开具发票成功');
    }

    // 保存发票
    public function saveInvoice()
    {
        $return = $this->db->ajaxSave();
        $this->layuiReturn('开具发票成功');
    }

    public function index()
    {
        $this->assign('cols', json_encode($this->cols));
        return $this->fetch();
    }

    public function pindex()
    {
        $this->assign('cols', json_encode($this->cols2));
        return $this->fetch();
    }

    public function finance()
    {
        $this->assign('cols', json_encode($this->cols_finance));
        return $this->fetch();
    }

    public function ajaxList()
    {
        $this->db->param ['site_id'] = SITE_ID;
        $return = $this->db->ajaxPage();
        $this->layuiReturn($return ['data'], $return ['count']);
    }

    public function ajaxApply()
    {
        $this->db->param ['site_id'] = -1;
        $this->db->param ['apply_state'] = 2;
        $this->db->param ['is_invoice'] = 2;
        $return = $this->db->ajaxPage();
        $this->layuiReturn($return ['data'], $return ['count']);
    }

    public function detail()
    {
        $this->assign('invoice_id', $this->post ['invoice_id']);
        $this->db->param ['site_id'] = -1;
        // $this->db->param['need_cart_info'] = 'yes';
        $data = $this->db->ajaxFind();
        $this->assign('data', $data);
        $this->assign('cols', json_encode($this->cols_detail));
        return $this->fetch();
    }

    public function views()
    {
        $this->assign('invoice_id', $this->post ['invoice_id']);
        $this->db->param ['site_id'] = -1;
        // $this->db->param['need_cart_info'] = 'yes';
        $data = $this->db->ajaxFind();
        $this->assign('data', $data);
        $this->assign('cols', json_encode($this->cols_detail));
        return $this->fetch();
    }

    public function ajaxDetail()
    {
        $cartdb = new Cartdb ();
        $cartdb->param = $this->post;
        $cartdb->param ['need_goods_title'] = 'yes';
        $cartdb->param ['site_id'] = -1;
        $data = $cartdb->ajaxSelect();
        $this->layuiReturn($data ['data'] ['list'], $data ['count']);
    }

    public function ajaxFind()
    {
        $this->db->param ['site_id'] = -1;
        $data = $this->db->ajaxFind();
        $this->layuiReturn($data);
    }

    // 选择客户
    public function customer()
    {
        $this->assign('wait_cols', json_encode($this->cols_wait_cart));
        $this->assign('select_cols', json_encode($this->cols_select_cart));
        return $this->fetch();
    }

    public function ajaxCustomer()
    {
        // 按收货人信息统计客户
        $shoppingdb = new Shoppingdb ();
        $shoppingdb->param = $this->post;
        $shoppingdb->param ['page'] = isset ($this->post ['page']) ? $this->post ['page'] : 1;
        $shoppingdb->param ['limit'] = $this->post ['limit'];
        $shoppingdb->param ['field'] = 'phone';
        $return = $shoppingdb->ajaxGroup();
        $this->layuiReturn($return ['data'], ceil($return ['count'] / $this->post ['limit']));
    }

    public function ajaxWaitCart()
    {
        $cartdb = new Cartdb ();
        $cartdb->param = $this->post;
        $cartdb->param ['order_no'] = '-1';
        $cartdb->param ['cart_id'] = '-1';
        if (isset ($this->post ['cart_id'])) {
            unset ($cartdb->param ['order_no']);
            $cartdb->param ['cart_id'] = explode(',', $this->post ['cart_id']);
        }
        if (isset ($this->post ['shopping_id'])) {
            unset ($cartdb->param ['cart_id']);
        }

        $order_no_arr = array();
        if (isset ($this->post ['shopping_id']) && $this->post ['shopping_id'] > 0) {
            // 调用配送信息
            $shoppingdb = new Shoppingdb ();
            $get_shopping = $shoppingdb->ajaxFind($this->post ['shopping_id']);
            $shoppingdb->param = array();
            $shoppingdb->param ['phone'] = $get_shopping ['phone'];
            $get_shopping_list = $shoppingdb->ajaxList();
            $shopping_id_arr = array();
            foreach ($get_shopping_list as $key => $val) {
                array_push($shopping_id_arr, $val ['shopping_id']);
            }
            $orderdb = new Orderdb ();
            $orderdb->param ['shopping_id'] = $shopping_id_arr;
            $orderdb->param ['site_id'] = -1;
            $orderdb->param ['order_state'] = array(
                2,
                3,
                4,
                5
            );
            $orderdb->param ['is_invoice'] = 3;
            $orderdb->param ['no_need_order_handle'] = 'yes';
            $orderdb->param ['_o'] = 'order_id';
            $orderdb->param ['_b'] = 'desc';
            $orderdb->param ['page'] = 1;
            $orderdb->param ['limit'] = 1000;
            if (isset ($this->post ['select_order_no']) && $this->post ['select_order_no']) {
                $orderdb->param ['order_no'] = $this->post ['select_order_no'];
            }
            $get_order = $orderdb->ajaxList();
            if (count($get_order) > 0) {
                foreach ($get_order as $key => $val) {
                    array_push($order_no_arr, $val ['order_no']);
                }
                $cartdb->param ['order_no'] = $order_no_arr;
            }
            // 调用已开票或申请开票信息
            $invoicedb = new Invoicedb ();
            $invoicedb->param ['state'] = array(
                1,
                2
            );
            $invoicedb->param ['apply_state'] = 1;
            $invoicedb->param ['member_id'] = $get_shopping ['member_id'];
            $invoicedb->param ['_o'] = 'invoice_id';
            $invoicedb->param ['_b'] = 'asc';
            $invoicedb->param ['page'] = 1;
            $invoicedb->param ['limit'] = 100;
            $invoicedb->param ['no_need_invoice_handle'] = 'yes';
            $get_invoice = $invoicedb->ajaxList();
            // 计算已开票，已选择 已申请的cart_id
            $no_cart_arr = '';
            foreach ($get_invoice as $key => $val) {
                $no_cart_arr .= $no_cart_arr ? ',' . $val ['cart_ids'] : $val ['cart_ids'];
            }
            if (isset ($this->post ['no_cart_id']) && $this->post ['no_cart_id']) {
                $no_cart_arr = $no_cart_arr ? $no_cart_arr . ',' . $this->post ['no_cart_id'] : $this->post ['no_cart_id'];
                $cartdb->param ['no_cart_id'] = explode(',', $this->post ['no_cart_id'] . ',' . $no_cart_arr);
            }
            if ($no_cart_arr) {
                $cartdb->param ['no_cart_id'] = explode(',', $no_cart_arr);
            }
        }
        $cartdb->param ['need_goods_info'] = 'yes';
        $cartdb->param ['no_need_attr'] = 'yes';
        $cartdb->param ['no_need_goods_handle'] = 'yes';
        $cartdb->param ['no_need_site'] = 'yes';
        $cartdb->param ['no_need_returned'] = 'yes';
        $cartdb->param ['no_need_install'] = 'yes';
        $cartdb->param ['invoice_state'] = 2;
        $cartdb->param ['site_id'] = -1;
        $return = $cartdb->ajaxSelect();
        $data = array();
        foreach ($return ['data'] as $key => $val) {
            $temp ['cart_id'] = $val ['cart_id'];
            $temp ['order_no'] = $val ['order_no'];
            $temp ['goods_name'] = $val ['goods_info'] ['goods_name'];
            $temp ['goods_unit'] = $val ['goods_info'] ['goods_unit'];
            $temp ['goods_num'] = $val ['goods_num'];
            $temp ['sale_price'] = $val ['goods_price'];
            $temp ['all_price'] = $val ['sum_sale_price'];
            array_push($data, $temp);
        }
        $this->layuiReturn($data, $return ['count']);
    }

    // 申请开票
    public function apply()
    {
        $this->assign('cols', json_encode($this->cols_apply));
        return $this->fetch();
    }

    public function ajaxDelete()
    {
        $this->db->ajaxDelete();
        $this->layuiReturn('删除成功');
    }

    // 验证码
    public function verify()
    {
        $data = rand(1000, 9999);
        $this->db->param ['field'] = 'draw_code';
        $this->db->param ['value'] = $data;
        $this->db->ajaxSave();
        $this->layuiReturn($data);
    }

    // 处理付款单信息
    public function saveStateFukuan()
    {
        $data = $this->post ['info'];
        $orderdb = new Orderdb ();
        $db = new Invoicedb ();
        $zip_name = 'uploads/hetong/fukuan' . time() . '.zip';
        $zip = new \ZipArchive ();
        $res = $zip->open($zip_name, \ZipArchive::CREATE);
        if (!$res) {
            halt('创建打包文件错误');
        }
        foreach ($data as $key => $val) {
            $get_order = $orderdb->useGlobalScope(false)->where('out_order_no', $val ['order_no'])->find();
            if ($get_order) {
                $get_order = $get_order->toArray();
                $db->useGlobalScope(false)->where('order_nos', $get_order ['order_no'])->update([
                    'order_fukuan' => $val ['state']
                ]);
                // 处理付款状态值
                $gys_pay_state = 4;
                if ($val['state'] == 2) {
                    // 全部付款
                    $gys_pay_state = 1;
                } elseif ($val['state'] == 3) {
                    //部分付款
                    $gys_pay_state = 3;
                } elseif ($val['state'] == 4) {
                    // 质保金付款
                    $gys_pay_state = 2;
                }
                $orderdb->useGlobalScope(false)->where('order_no', $get_order ['order_no'])->update([
                    //   'pay_state' => $val ['state'],
                    //   'pay_time' => time(),
                    'ghs_pay' => $gys_pay_state,
                    'ghs_pay_time' => time()
                ]);

                // 修改请款状态
                $qinkuandb = new Qingkuandb();
                $qinkuandb->where('out_order_no', $get_order['out_order_no'])->update(['zhifu' => $gys_pay_state == 1 ? 1 : 0]);
                // 结束

                // 推送接口
                $msg_param = [];
                $msg_param['order_no'] = $get_order['out_order_no'];
                $msg_param['state'] = $gys_pay_state;
                $msg_param['time'] = time();
                pushTljMsg('order_payment', $msg_param, $get_order['supplier_id']);
                // 结束推送接口

                // 日志
                $order_logdb = new OrderLogdb ();
                $order_logdb->param = array(
                    'type_index' => 12,
                    'order_no' => $get_order ['order_no'],
                    'member_id' => MEMBER_ID,
                    'view_text' => '订单付款',
                    'post_json' => $get_order
                );
                $order_logdb->saveData();
                // 添加发票信息到zip文件中
                if ($get_order ['cght']) {
                    $ht_src = str_replace('https://tailongji.dixintong.com/', '', str_replace($this->base_url, '', $get_order ['cght']));
                    $zip->addFile($ht_src, $get_order['out_order_no'] . '采购合同.pdf');
                }
            }
        }
        $zip->close();
        $UOrderdb = new UOrderdb();
        $UOrderdb->param['data'] = $data;
        $UOrderdb->saveFukuan();
        Cache::clear('order');
        Cache::clear('invoice');
        $this->layuiReturn('success', 'https://tailongji.dixintong.com/' . $zip_name);
    }

    public function saveState()
    {
        $data = $this->post ['info'];
        $orderdb = new Orderdb ();
        $db = new Invoicedb ();
        foreach ($data as $key => $val) {
            $get_order = $orderdb->useGlobalScope(false)->where('out_order_no', $val ['order_no'])->find();
            if ($get_order) {
                $get_order = $get_order->toArray();
                $db->useGlobalScope(false)->where('order_nos', $get_order ['order_no'])->update([
                    'order_shoukuan' => $val ['state']
                ]);
                $orderdb->useGlobalScope(false)->where('order_no', $get_order ['order_no'])->update([
                    'pay_state' => $val ['state'],
                    'pay_time' => time()
                ]);
                // 推送接口
                $msg_param = [];
                $msg_param['order_no'] = $get_order['out_order_no'];
                $msg_param['state'] = $val ['state'];
                $msg_param['time'] = time();
                pushTljMsg('order_pay', $msg_param, $get_order['supplier_id']);
                // 结束推送接口
                // 日志
                $order_logdb = new OrderLogdb ();
                $order_logdb->param = array(
                    'type_index' => 12,
                    'order_no' => $get_order ['order_no'],
                    'member_id' => MEMBER_ID,
                    'view_text' => '订单收款',
                    'post_json' => $get_order
                );
                $order_logdb->saveData();
            }

        }
        $UOrderdb = new UOrderdb();
        $UOrderdb->param['data'] = $data;
        $UOrderdb->saveShoukuan();
        Cache::clear('order');
        Cache::clear('invoice');
        $this->layuiReturn('success');
    }

    public function daoru()
    {
        return $this->fetch();
    }

    public function daorufukuan()
    {
        return $this->fetch();
    }

    // 发送验证码
    public function sendSms()
    {
        $order_nos = $this->post ['order_nos'];
        if ($this->post ['send_type'] == 'shoukuan') {
            $this->layuiReturn('success');
            exit();
            // 上面两行是暂时屏蔽收款通知
            $code = 'SMS_227262896';
            $data = Db::table('__INVOICE__ i')->where('i.order_nos', 'IN', $order_nos)->join('__ORDER__ o', 'o.order_no = i.order_nos')->join('__MEMBER__ m', 'm.member_id = o.supplier_id')->field('o.order_no,m.phone,o.order_money,o.out_order_no')->select();
        } elseif ($this->post ['send_type'] == 'cuipiao') {
            // 催票短信
            $code = 'SMS_227745179';
            $data = Db::table('__INVOICE__ i')->where('i.order_nos', 'IN', $order_nos)->join('__ORDER__ o', 'o.order_no = i.order_nos')->join('__MEMBER__ m', 'm.member_id = o.supplier_id')->field('o.order_no,m.phone,o.order_money,o.out_order_no')->select();
        } else {
            $code = 'SMS_227247921';
            $data = Db::table('__INVOICE__ i')->where('i.order_nos', 'IN', $order_nos)->join('__ORDER__ o', 'o.order_no = i.order_nos')->join('__MEMBER__ m', 'm.member_id = o.supplier_id')->field('o.order_no,m.phone,o.order_money,o.out_order_no')->select();
        }
        if (!$data->isEmpty()) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $msg_json ['order'] = $val ['out_order_no'];
                if ($this->post ['send_type'] != 'cuipiao') {
                    $msg_json ['money'] = $val ['order_money'] / 100;
                }
                $result = $this->sendMsg($val ['phone'], $code, $msg_json);
                if ($this->post ['send_type'] == 'shoukuan') {
                    $this->db->save([
                        'send_msg' => 1
                    ], [
                        'order_nos' => $val ['order_no']
                    ]);
                }
            }
        }
        $this->layuiReturn('success');
    }

    // 导出库房采购发票
    public function excelGysInvoice($invoice_ids)
    {
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '采购发票：' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '单位名称',
            '纳税识别号',
            '地址、电话',
            '开户行及账号',
            '税务大类',
            '税务编号',
            '货物名称',
            '规格型号',
            '数量',
            '单位',
            '采购单价（元）',
            '采购金额（元）',
            '订单号'
        );
        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $get_data = $this->db->where('invoice_id', 'IN', explode(',', $invoice_ids))->select()->toArray();
        foreach ($get_data as $key => $val) {
            $get_cart = Db::table('__CART__ c')->where('c.order_no', $val ['order_nos'])->where('g.site_id', SITE_ID)->join('__GOODS__ g', 'g.goods_sku = c.goods_sku')->join('__ORDER__ o', 'o.order_no = c.order_no')->select();
            $get_data [$key] ['cart_info'] = $get_cart->toArray();
        }
        $excel_data = array();
        foreach ($get_data as $key => $val) {
            foreach ($val ['cart_info'] as $k => $v) {
                unset ($temp);

                // $temp [0] = $val ['invoice_title'];
                // $temp [1] = $val ['invoice_duty'];
                // $temp [2] = $val ['invoice_addr'] . ' ' . $val ['invoice_tel'];
                $temp [0] = '北京市泰龙吉贸易有限公司';
                $temp [1] = '91110105675715354X';
                $temp [2] = '北京市朝阳区管庄乡杨闸村京通辅路南8号院 F1 010-59521909';
                $temp [3] = '交通银行北京林萃路支行  110061203018010014524';
                $temp [4] = $v ['product_area'];
                $temp [5] = "\t" . $v ['shuiwu_id'];
                $temp [6] = $v ['product_firm'];
                $temp [7] = $v ['goods_model'];
                $temp [8] = $v ['goods_num'];
                $temp [9] = $v ['goods_unit'];
                if ($v ['supplier_rate'] > 0) {
                    $cg_price = round($v ['goods_price'] * $v ['supplier_rate']) / 100;
                } else {
                    $cg_price = $v ['goods_price'];
                }
                $temp [10] = ' ' . number_format($cg_price, 2, '.', '');
                $temp [11] = ' ' . number_format($temp [8] * $cg_price, 2, '.', '');
                $temp [12] = "\t" . $v ['out_order_no'];
                array_push($excel_data, $temp);
            }
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody4($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);
        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    // 导出销售发票
    public function excelSaleInvoice($invoice_ids)
    {
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '销售发票：' . date('Ymdhi') . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '订单号',
            '单位名称',
            '联系电话',
            '税务大类',
            '税务编号',
            '货物名称',
            '规格型号',
            '数量',
            '单位',
            '销售单价（元）',
            '销售金额（元）',
            ' '
        );
        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $get_data = $this->db->where('invoice_id', 'IN', explode(',', $invoice_ids))->select()->toArray();
        foreach ($get_data as $key => $val) {
            $get_cart = Db::table('__CART__ c')->where('c.order_no', $val ['order_nos'])->where('g.site_id', SITE_ID)->join('__GOODS__ g', 'g.goods_sku = c.goods_sku')->join('__ORDER__ o', 'o.order_no = c.order_no')->select();
            $get_data [$key] ['cart_info'] = $get_cart->toArray();
        }
        $excel_data = array();
        foreach ($get_data as $key => $val) {
            foreach ($val ['cart_info'] as $k => $v) {
                $t = json_decode($v ['api_param'], true);
                unset ($temp);
                $temp [0] = "\t" . $v ['out_order_no'];
                $temp [1] = $val ['invoice_title'];
                // $temp [1] = $val ['invoice_duty'];
                $temp [2] = $t ['mobile'];
                $temp [3] = $v ['product_area'];
                $temp [4] = "\t" . $v ['shuiwu_id'];
                $temp [5] = $v ['product_firm'];
                $temp [6] = $v ['goods_model'];
                $temp [7] = $v ['goods_num'];
                $temp [8] = $v ['goods_unit'];
                $temp [9] = ' ' . number_format($v ['goods_price'], 2, '.', '');
                $temp [10] = ' ' . number_format($temp [7] * $v ['goods_price'], 2, '.', '');
                $temp [11] = '';

                array_push($excel_data, $temp);
            }
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);
        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    protected function setExcelHeader($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data) - 1; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
            } else {
                $cell_value = chr($start + $i) . '1';
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension(chr($start + $i))->setWidth(20);
        }
    }

    protected function setExcelBody4($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count - 1; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, $val [$i]);
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [12] != $temp) {
                $temp = $data [$x] [12];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 4; $y++) {
                        $cell_value = chr($start + $y);
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 4; $y++) {
                $cell_value = chr($start + $y);
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

    protected function setExcelBody($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count - 1; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, $val [$i]);
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 3; $y++) {
                        $cell_value = chr($start + $y);
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 3; $y++) {
                $cell_value = chr($start + $y);
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

    // 导出收款发票
    public function shoukuanfapiao($file)
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $file = str_replace('http', '', str_replace('https', '', $file));
        $file = str_replace('://' . $_SERVER ['HTTP_HOST'], '.', $file);
        vendor("PHPExcel.PHPExcel");
        Vendor('PHPExcel.Classes.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.Classes.PHPExcel.Writer.Excel2007');
        $phpExcel = new \PHPExcel ();
        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($extension == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        } else if ($extension == 'xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        // $objReader = \PHPExcel_IOFactory::createReader ( 'Excel2007' );
        $objPHPExcel = $objReader->load($file);
        $sheet = $objPHPExcel->getSheet(0);
        $allColumn = $sheet->getHighestColumn();
        $allRow = $sheet->getHighestRow();
        $allColumn = $sheet->getHighestColumn();
        $allRow = $sheet->getHighestRow();
        $ColumnNum = \PHPExcel_Cell::columnIndexFromString($allColumn);
        $data = array();
        $order_arr = [];
        $order_price = [];
        for ($rowIndex = 2; $rowIndex <= $allRow; $rowIndex++) { // 循环读取每个单元格的内容。注意行从1开始，列从A开始
            if ($sheet->getCellByColumnAndRow(0, $rowIndex)->getValue()) {
                $out_order_no = $sheet->getCellByColumnAndRow(0, $rowIndex)->getValue();
                $excel_price = number_format($sheet->getCellByColumnAndRow(1, $rowIndex)->getValue() * 100, 0, '', '');
                array_push($order_arr, $out_order_no);
                if (isset($order_price[$out_order_no])) {
                    $order_price[$out_order_no] += $excel_price;
                } else {
                    $order_price[$out_order_no] = $excel_price;
                }
            }
        }
        if (count($order_arr) > 0) {
            $orderdb = new Orderdb();
            $get_order = $orderdb->whereIn('out_order_no', $order_arr)->field('cght,out_order_no,order_money')->select();
            if (!$get_order->isEmpty()) {
                $zip_name = 'uploads/hetong/shoukuan' . time() . '.zip';
                $zip = new \ZipArchive ();
                $res = $zip->open($zip_name, \ZipArchive::CREATE);
                if (!$res) {
                    halt('创建打包文件错误');
                }
                $excel_data = [];
                foreach ($get_order as $key => $val) {
                    $fit_flag = 1;
                    if ($order_price[$val['out_order_no']] != number_format($val['order_money'], 0, '', '')) {
                        $fit_flag = 0;
                        $temp = [];
                        $temp['out_order_no'] = $val['out_order_no'];
                        $temp['order_money'] = (int)$val['order_money'];
                        $temp['excel_money'] = (int)$order_price[$val['out_order_no']];
                        array_push($excel_data, $temp);
                    }
                    if ($val ['cght']) {
                        $ht_src = str_replace('https://tailongji.dixintong.com/', '', str_replace($this->base_url, '', $val ['cght']));
                        if ($fit_flag) {
                            $zip->addFile($ht_src, $val['out_order_no'] . '采购合同.pdf');
                        } else {
                            $zip->addFile($ht_src, 'no_fit/' . $val['out_order_no'] . '采购合同.pdf');
                        }
                    }
                }

                // 如果有不匹配的数据 添加excel文档
                if (count($excel_data)) {
                    $excel_name = '未匹配信息.xls';
                    $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
                    $obj_act_sheet = $phpExcel->getActiveSheet();
                    $header_data = array(
                        '订单号',
                        '订单金额',
                        '导入金额',
                        ' '
                    );
                    $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
                    $down_data = [];
                    foreach ($excel_data as $key => $val) {
                        // 处理文件夹名称
                        $temp = [];
                        $temp[0] = $val['out_order_no'];
                        $temp[1] = $val['order_money'] / 100;
                        $temp[2] = $val['excel_money'] / 100;
                        $temp[3] = '';
                        array_push($down_data, $temp);
                    }
                    $vAlign = new \PHPExcel_Style_Alignment ();
                    $this->setExcelBodyInvoice($obj_act_sheet, $phpExcel, $down_data, count($header_data), $vAlign::VERTICAL_CENTER);
                    $obj_write->save('./uploads/Excel/zip/' . $excel_name);
                    $zip->addFile('./uploads/Excel/zip/' . $excel_name, 'no_fit/' . $excel_name);
                }

                $zip->close();
                $this->layuiReturn('success', 'https://tailongji.dixintong.com/' . $zip_name);
            } else {
                $this->layuiReturn('error', '没有可导出信息2', -1);
            }
        } else {
            $this->layuiReturn('error', '没有可导出信息', -1);
        }
        halt($order_arr);
    }

    // 导出查询发票
    public function searchExport()
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $this->db->param ['site_id'] = SITE_ID;
        $this->db->param['_o'] = 'invoice_id';
        $this->db->param['_b'] = 'asc';
        $this->db->param['no_need_proof'] = 'yes';
        if (!isset($this->db->param['order_shoukuan'])) {
            $this->db->param['order_shoukuan'] = [2, 3, 4];
        }
        $result = $this->db->ajaxSearch();
        if ($result) {
            vendor("PHPExcel.PHPExcel");
            $phpExcel = new \PHPExcel ();
            ob_end_clean();
            $excel_name = '导出订单付款查询结果' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
            $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
            $obj_act_sheet = $phpExcel->getActiveSheet();
            $header_data = array(
                '军采订单号',
                '供应商',
                '开票金额',
                '采购发票号',
                '用户发票',
                '收款',
                '采购发票',
                '发票审核',
                '付款',
                '地址',
                ''
            );
            $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
            $state_arr = ['未开票', '已开票', '申请开票中', '发票红冲'];
            $shoukuan_arr = ['未收款', '全部收款', '部分收款', '质保金收款'];
            $fukuan_arr = ['未付款', '全部付款', '不分付款', '质保金付款'];
            $zip_name = 'uploads/hetong/fukuans' . time() . '.zip';
            $zip = new \ZipArchive ();
            $res = $zip->open($zip_name, \ZipArchive::CREATE);
            if (!$res) {
                halt('创建打包文件错误');
            }
            $excel_data = [];
            foreach ($result as $key => $val) {
                if (isset($val['caigou_hetong']) && $val ['caigou_hetong']) {
                    $ht_src = str_replace('https://tailongji.dixintong.com/', '', str_replace($this->base_url, '', $val ['caigou_hetong']));
                    $zip->addFile($ht_src, $val['out_order_no'] . '采购合同.pdf');
                }
            }
            foreach ($result as $key => $val) {
                $temp [0] = "\t" . $val ['out_order_no'];// 军采订单号
                $temp [1] = $val['supplier_name']; // 供应商
                $temp [2] = $val['invoice_money']; // 开票金额
                $temp [3] = "\t" . $val['caigou_invoice_duty']; // 采购发票号
                // 用户发票
                if (in_array($val['state'], [1, 2, 3, 4])) {
                    $temp [4] = $state_arr[$val['state'] - 1];
                } else {
                    $temp [4] = '未知';
                }
                // 收款
                if (in_array($val['order_shoukuan'], [1, 2, 3, 4])) {
                    $temp [5] = $shoukuan_arr[$val['order_shoukuan'] - 1];
                } else {
                    $temp [5] = '未知';
                }
                // 采购发票
                $temp [6] = $val['gys_state'] == 0 ? '未开' : '已开';
                // 发票审核
                $temp [7] = $val['caigou_state'] == 1 ? '已审核' : '未审核';
                // 发票付款
                if (in_array($val['order_fukuan'], [1, 2, 3, 4])) {
                    $temp [8] = $fukuan_arr[$val['order_fukuan'] - 1];
                } else {
                    $temp [8] = '未付款';
                }
                $temp[9] = $val ['caigou_hetong'];
                $temp[10] = '';
                array_push($excel_data, $temp);
            }
            $vAlign = new \PHPExcel_Style_Alignment ();
            $this->setExcelBody($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

            $obj_write->save('./uploads/Excel/zip/' . $excel_name);
            $zip->addFile('./uploads/Excel/zip/' . $excel_name, 'excel/' . $excel_name);
            $this->layuiReturn('https://tailongji.dixintong.com/' . $zip_name, 'https://tailongji.dixintong.com/' . $zip_name);
        } else {
            $this->layuiReturn('未查询到数据', '未查询到数据', -1);
        }


    }

    // 导出请款发票
    public function qingkuanfapiao($file)
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $file = str_replace('http', '', str_replace('https', '', $file));
        $file = str_replace('://' . $_SERVER ['HTTP_HOST'], '.', $file);
        vendor("PHPExcel.PHPExcel");
        Vendor('PHPExcel.Classes.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.Classes.PHPExcel.Writer.Excel2007');
        $phpExcel = new \PHPExcel ();
        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($extension == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        } else if ($extension == 'xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        // $objReader = \PHPExcel_IOFactory::createReader ( 'Excel2007' );
        $objPHPExcel = $objReader->load($file);
        $sheet = $objPHPExcel->getSheet(0);
        $allColumn = $sheet->getHighestColumn();
        $allRow = $sheet->getHighestRow();
        $allColumn = $sheet->getHighestColumn();
        $allRow = $sheet->getHighestRow();
        $ColumnNum = \PHPExcel_Cell::columnIndexFromString($allColumn);
        $data = array();
        $order_arr = [];
        $order_price = [];
        for ($rowIndex = 2; $rowIndex <= $allRow; $rowIndex++) { // 循环读取每个单元格的内容。注意行从1开始，列从A开始
            if ($sheet->getCellByColumnAndRow(0, $rowIndex)->getValue()) {
                $out_order_no = $sheet->getCellByColumnAndRow(0, $rowIndex)->getValue();
                $excel_price = number_format($sheet->getCellByColumnAndRow(1, $rowIndex)->getValue() * 100, 0, '', '');
                array_push($order_arr, $out_order_no);
                if (isset($order_price[$out_order_no])) {
                    $order_price[$out_order_no] += $excel_price;
                } else {
                    $order_price[$out_order_no] = $excel_price;
                }
            }
        }
        if (count($order_arr) > 0) {
            $orderdb = new Orderdb();
            $get_order = $orderdb->whereIn('out_order_no', $order_arr)->field('cght,out_order_no,order_money')->select();
            if (!$get_order->isEmpty()) {
                $zip_name = 'uploads/hetong/fukuan' . time() . '.zip';
                $zip = new \ZipArchive ();
                $res = $zip->open($zip_name, \ZipArchive::CREATE);
                if (!$res) {
                    halt('创建打包文件错误');
                }
                $excel_data = [];
                foreach ($get_order as $key => $val) {
                    $fit_flag = 1;
                    if ($order_price[$val['out_order_no']] != number_format($val['order_money'], 0, '', '')) {
                        $fit_flag = 0;
                        $temp = [];
                        $temp['out_order_no'] = $val['out_order_no'];
                        $temp['order_money'] = (int)$val['order_money'];
                        $temp['excel_money'] = (int)$order_price[$val['out_order_no']];
                        array_push($excel_data, $temp);
                    }
                    if ($val ['cght']) {
                        $ht_src = str_replace('https://tailongji.dixintong.com/', '', str_replace($this->base_url, '', $val ['cght']));
                        if ($fit_flag) {
                            $zip->addFile($ht_src, $val['out_order_no'] . '采购合同.pdf');
                        } else {
                            $zip->addFile($ht_src, 'no_fit/' . $val['out_order_no'] . '采购合同.pdf');
                        }
                    }
                }

                // 如果有不匹配的数据 添加excel文档
                if (count($excel_data)) {
                    $excel_name = '未匹配信息.xls';
                    $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
                    $obj_act_sheet = $phpExcel->getActiveSheet();
                    $header_data = array(
                        '订单号',
                        '订单金额',
                        '导入金额',
                        ' '
                    );
                    $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
                    $down_data = [];
                    foreach ($excel_data as $key => $val) {
                        // 处理文件夹名称
                        $temp = [];
                        $temp[0] = $val['out_order_no'];
                        $temp[1] = $val['order_money'] / 100;
                        $temp[2] = $val['excel_money'] / 100;
                        $temp[3] = '';
                        array_push($down_data, $temp);
                    }
                    $vAlign = new \PHPExcel_Style_Alignment ();
                    $this->setExcelBodyInvoice($obj_act_sheet, $phpExcel, $down_data, count($header_data), $vAlign::VERTICAL_CENTER);
                    $obj_write->save('./uploads/Excel/zip/' . $excel_name);
                    $zip->addFile('./uploads/Excel/zip/' . $excel_name, 'no_fit/' . $excel_name);
                }

                $zip->close();
                $this->layuiReturn('success', 'https://tailongji.dixintong.com/' . $zip_name);
            } else {
                $this->layuiReturn('error', '没有可导出信息2', -1);
            }
        } else {
            $this->layuiReturn('error', '没有可导出信息', -1);
        }
        halt($order_arr);
    }

    protected function setExcelBodyInvoice($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 35; $y++) {
                        $cell_value = chr($start + $y);
                        if ($y >= 26) {
                            $cell_value = 'A' . chr($start + $y - 26);
                        }
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 35; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 26) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

    // 导入付款excel
    public function excelFukuan($file)
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $file = str_replace('http', '', str_replace('https', '', $file));
        $file = str_replace('://' . $_SERVER ['HTTP_HOST'], '.', $file);
        vendor("PHPExcel.PHPExcel");
        Vendor('PHPExcel.Classes.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.Classes.PHPExcel.Writer.Excel2007');
        $phpExcel = new \PHPExcel ();
        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($extension == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        } else if ($extension == 'xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        // $objReader = \PHPExcel_IOFactory::createReader ( 'Excel2007' );
        $objPHPExcel = $objReader->load($file);
        $sheet = $objPHPExcel->getSheet(0);
        $allColumn = $sheet->getHighestColumn();
        $allRow = $sheet->getHighestRow();
        $allColumn = $sheet->getHighestColumn();
        $allRow = $sheet->getHighestRow();
        $ColumnNum = \PHPExcel_Cell::columnIndexFromString($allColumn);
        $data = array();
        for ($rowIndex = 2; $rowIndex <= $allRow; $rowIndex++) { // 循环读取每个单元格的内容。注意行从1开始，列从A开始
            for ($colIndex = 0; $colIndex < $ColumnNum; $colIndex++) {
                if ($sheet->getCellByColumnAndRow(0, $rowIndex)->getValue()) {
                    if ($colIndex == 0) {
                        $value = $sheet->getCellByColumnAndRow($colIndex, $rowIndex)->getValue();
                        //$value = gmdate ( 'Y-m-d', \PHPExcel_Shared_Date::ExcelToPHP ( $sheet->getCellByColumnAndRow ( $colIndex, $rowIndex )->getValue () ) );
                    } else {
                        $value = $sheet->getCellByColumnAndRow($colIndex, $rowIndex)->getValue();
                    }
                    $data [$rowIndex - 2] [] = ( string )$value;
                }
            }
        }
        $new_data = array();
        $out_data = array();
        foreach ($data as $key => $val) {
            $temp ['order_no'] = $val [0];
            $temp ['money'] = $val [1];
            array_push($new_data, $temp);
        }
        $ok_data = array();
        foreach ($new_data as $key => $val) {
            $chk = Db::table('__INVOICE__ i')
                ->where('o.out_order_no', $val ['order_no'])
                ->join('__ORDER__ o', 'o.order_no = i.order_nos')
                ->join('__MEMBER__ m', 'o.supplier_id = m.member_id')
                ->field('i.invoice_money,o.out_order_no,o.huikuandanwei,m.supplier_name,m.yinhang,m.zhanghao')
                ->find();
            if ($chk) {
                $order_money = $chk ['invoice_money'] / 100;
                $shoukuan_money = $val ['money'];
                $state_text = '';
                $state = 0;
                if (floatval($shoukuan_money) == floatval($order_money)) {
                    $state_text = '全部付款';
                    $state = 2;
                } else if (floatval($shoukuan_money) == floatval($order_money) * 0.95) {
                    $state_text = '质保金付款';
                    $state = 4;
                } else if (floatval($shoukuan_money) == floatval($order_money) * 0.97) {
                    $state_text = '质保金付款';
                    $state = 4;
                } else {
                    $state_text = '部分付款';
                    $state = 3;
                }
                $new_data [$key] ['state_text'] = $state_text;
                $new_data [$key] ['state'] = $state;
                $new_data[$key]['supplier_name'] = $chk['supplier_name'];
                $new_data[$key]['yinhang'] = $chk['yinhang'];
                $new_data[$key]['zhanghao'] = $chk['zhanghao'];
                array_push($ok_data, $new_data [$key]);
            } else {
                $new_data [$key] ['state_text'] = '未找到订单号';
                $new_data [$key] ['state'] = -1;
                array_push($out_data, $new_data [$key]);
            }
        }
        $result ['ok'] = $ok_data;
        $result ['out'] = $out_data;
        $this->layuiReturn($result);
    }

    // 导入excel
    public function excel($file)
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $file = str_replace($_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'], '.', $file);
        vendor("PHPExcel.PHPExcel");
        Vendor('PHPExcel.Classes.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.Classes.PHPExcel.Writer.Excel2007');
        $phpExcel = new \PHPExcel ();
        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($extension == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        } else if ($extension == 'xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        // $objReader = \PHPExcel_IOFactory::createReader ( 'Excel2007' );
        $objPHPExcel = $objReader->load($file);
        $sheet = $objPHPExcel->getSheet(0);
        $allColumn = $sheet->getHighestColumn();
        $allRow = $sheet->getHighestRow();
        $allColumn = $sheet->getHighestColumn();
        $allRow = $sheet->getHighestRow();
        $ColumnNum = \PHPExcel_Cell::columnIndexFromString($allColumn);
        $data = array();
        for ($rowIndex = 2; $rowIndex <= $allRow; $rowIndex++) { // 循环读取每个单元格的内容。注意行从1开始，列从A开始
            for ($colIndex = 0; $colIndex < $ColumnNum; $colIndex++) {
                if ($sheet->getCellByColumnAndRow(0, $rowIndex)->getValue()) {
                    if ($colIndex == 0) {
                        $value = $sheet->getCellByColumnAndRow($colIndex, $rowIndex)->getValue();
                        //$value = gmdate ( 'Y-m-d', \PHPExcel_Shared_Date::ExcelToPHP ( $sheet->getCellByColumnAndRow ( $colIndex, $rowIndex )->getValue () ) );
                    } else {
                        $value = $sheet->getCellByColumnAndRow($colIndex, $rowIndex)->getValue();
                    }
                    $data [$rowIndex - 2] [] = ( string )$value;
                }
            }
        }
        $new_data = array();
        $out_data = array();
        foreach ($data as $key => $val) {
            $temp ['date'] = $val [0];
            $temp ['title'] = $val [1];
            $temp ['intro'] = $val [2];
            $temp ['money'] = $val [3];
            $temp ['order_no'] = $val [4];
            $t = explode(chr(10), $temp ['order_no']);
            if (count($t) == 1) {
                array_push($new_data, $temp);
            } else {
                $sum_price = 0;
                $son_data = array();
                for ($i = 0; $i < count($t); $i++) {
                    $t1 = explode('（', $t [$i]);
                    $order_no = $t1 [0];
                    $price = str_replace('）', '', $t1 [1]);
                    $sum_price += floatval($price);
                    $temp1 ['date'] = $val [0];
                    $temp1 ['title'] = $val [1];
                    $temp1 ['intro'] = $val [2];
                    $temp1 ['money'] = $price;
                    $temp1 ['order_no'] = $order_no;
                    array_push($son_data, $temp1);
                }
                if (floatval($temp ['money']) == $sum_price) {
                    for ($i = 0; $i < count($son_data); $i++) {
                        array_push($new_data, $son_data [$i]);
                    }
                } else {
                    $temp ['state_text'] = '金额不匹配';
                    $temp ['state'] = -1;
                    $temp ['order_no'] = str_replace(chr(10), '<br />', $temp ['order_no']);
                    array_push($out_data, $temp);
                }
            }
        }
        $ok_data = array();
        foreach ($new_data as $key => $val) {
            $chk = Db::table('__INVOICE__ i')->where('o.out_order_no', $val ['order_no'])->join('__ORDER__ o', 'o.order_no = i.order_nos')->field('i.invoice_money,o.out_order_no,o.huikuandanwei')->find();
            if ($chk) {
                if ($chk ['huikuandanwei'] != $val ['title']) {
                    $new_data [$key] ['state_text'] = '汇款单位不匹配';
                    $new_data [$key] ['state'] = -1;
                    array_push($out_data, $new_data [$key]);
                } else {
                    $order_money = $chk ['invoice_money'] / 100;
                    $shoukuan_money = $val ['money'];
                    $state_text = '';
                    $state = 0;
                    if (floatval($shoukuan_money) == floatval($order_money)) {
                        $state_text = '全部收款';
                        $state = 2;
                    } else if (floatval($shoukuan_money) == floatval($order_money) * 0.95) {
                        $state_text = '质保金收款';
                        $state = 4;
                    } else if (number_format(floatval($shoukuan_money), 2, '.', '') == number_format(floatval($order_money) * 0.97, 2, '.', '')) {
                        $state_text = '质保金收款';
                        $state = 4;
                    } else {
                        $state_text = '部分收款';
                        $state = 3;
                    }
                    $new_data [$key] ['state_text'] = $state_text;
                    $new_data [$key] ['state'] = $state;
                    array_push($ok_data, $new_data [$key]);
                }
            } else {
                $new_data [$key] ['state_text'] = '未找到订单号';
                $new_data [$key] ['state'] = -1;
                array_push($out_data, $new_data [$key]);
            }
        }
        $result ['ok'] = $ok_data;
        $result ['out'] = $out_data;
        $this->layuiReturn($result);
    }

    // 导出未匹配的订单号
    public function outOrderFukuan()
    {
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '订单号',
            '金额',
            '说明'
        );
        $this->setExcelHeader2($obj_act_sheet, $phpExcel, $header_data);
        $get_data = $this->post ['param'];
        $excel_data = array();
        foreach ($get_data as $key => $val) {
            unset ($temp);
            $temp [0] = $val ['order_no'];
            $temp [1] = $val ['money'];
            $temp [2] = $val ['state_text'];
            array_push($excel_data, $temp);
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody2($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);
        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    // 导出未匹配的订单号
    public function outOrder()
    {
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '日期',
            '汇款单位',
            '摘要',
            '金额',
            '订单号',
            '说明'
        );
        $this->setExcelHeader2($obj_act_sheet, $phpExcel, $header_data);
        $get_data = $this->post ['param'];
        $excel_data = array();
        foreach ($get_data as $key => $val) {
            unset ($temp);
            $temp [0] = $val ['date'];
            $temp [1] = $val ['title'];
            $temp [2] = $val ['intro'];
            $temp [3] = $val ['money'];
            $temp [4] = str_replace('<br />', chr(10), $val ['order_no']);
            $temp [5] = $val ['state_text'];
            array_push($excel_data, $temp);
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody2($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);
        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    protected function setExcelBody2($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, $val [$i]);
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
    }

    protected function setExcelHeader2($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
            } else {
                $cell_value = chr($start + $i) . '1';
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension(chr($start + $i))->setWidth(20);
        }
    }
}